package com.lbb.waimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbb.waimai.entiry.Category;
import com.lbb.waimai.entiry.Order;
import com.lbb.waimai.entiry.ShoppingCart;
import com.lbb.waimai.entiry.User;
import com.lbb.waimai.entiry.vo.OrderVo;
import com.lbb.waimai.entiry.vo.PageVo;
import com.lbb.waimai.mapper.CategoryMapper;
import com.lbb.waimai.mapper.OrderMapper;
import com.lbb.waimai.service.CategoryService;
import com.lbb.waimai.service.OrderService;
import com.lbb.waimai.service.ShoppingCartService;
import com.lbb.waimai.service.UserService;
import lombok.Data;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;


    //生成订单，根据这个用户的id以及他购物车对应的菜品
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toOrder(Long userId, OrderVo orderVo) {
        List<ShoppingCart> shoppingCartList = shoppingCartService.findInCart(userId);
        if (shoppingCartList.size()==0){
            throw new RuntimeException("购物车为空");
        }
        Integer uid = Integer.valueOf(userId.toString());
        User user = userService.getById(uid);

        Order order = new Order();
        order.setStatus(0);
        order.setOffTime(orderVo.getTime());
        if (!StringUtils.isEmpty(orderVo.getInfo())){
            order.setInfo(orderVo.getInfo());
        }
        order.setUNikeName(user.getNikeName());

        order.setUAddr(user.getAddr());
        order.setCreateTime(new Date());
        System.out.println("订单创建时间"+order.getCreateTime());
        System.out.println("订单配送时间"+order.getOffTime());

        //查询出购物车总订单金额
        double totalPrice = 0;
        for (ShoppingCart cart : shoppingCartList) {
            totalPrice += cart.getFSum();
        }
        order.setTotalPrice(new BigDecimal(totalPrice));
        order.setUId(uid);
        baseMapper.insert(order);
        //生成订单后清空购物车
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id",uid);
        shoppingCartService.remove(wrapper);

    }

    //取出所有的订单0未支付，1已支付，2取消支付
    @Override
    public List<Order> getOrder(Long userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id", Integer.valueOf(userId.toString()));
        wrapper.orderByDesc("create_time");
        List<Order> orders = baseMapper.selectList(wrapper);
        return orders;
    }

    //取消订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrder(Integer id, Long userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id", Integer.valueOf(userId.toString()));
        wrapper.eq("id", id);
        Order order = baseMapper.selectOne(wrapper);
        Date offTime = order.getOffTime();
        //规定取餐时间与当前时间相隔小于5小时无法取消
        if (offTime.getTime() - (new Date().getTime() )  < 5 * 3600000){
            throw new RuntimeException("距离取餐时间不足5小时，无法取消");
        }
        if (order != null) {
            //设置为申请退款
            order.setStatus(4);
            baseMapper.updateById(order);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void payOrder(Integer id) {
       try {
           Thread.sleep(3000);
       }catch (Exception e){
           e.printStackTrace();
       }
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Order order = baseMapper.selectOne(wrapper);
        if (order != null) {
            order.setStatus(1);
            order.setOrderNumber(UUID.randomUUID().toString().replace("-",""));
            baseMapper.updateById(order);
        }
    }

    //分页查询所有订单
    @Override
    public Page<Order> findAllOrder(PageVo pageVo) {
        int currentPage = pageVo.getCurrent();
        int pageSize = pageVo.getSize();
        Page<Order> page = new Page<>(currentPage,pageSize);
        Page<Order> orderPage = page(page);
        return orderPage;
    }
}
